﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.Utility.Helper
{
    /// <summary>
    /// Csv助手类
    /// </summary>
    public static class CsvHelper
    {

        /// <summary>
        /// 以Rfc4180标准写入,参考：<see href="https://www.codeproject.com/Tips/665519/Writing-a-DataTable-to-a-CSV-file"/>
        /// <code>
        /// using (StreamWriter writer = new StreamWriter("C:\\Temp\\dump.csv")) {
        ///     CsvHelper.Rfc4180Writer(sourceTable, writer, true);
        /// }
        /// </code>
        /// </summary>
        /// <param name="sourceTable">数据源</param>
        /// <param name="filePath">要写入文件的完整路径</param>
        /// <param name="isAppend">文件存在是否追加数据</param>
        /// <param name="encoding">文件编码，为null则使用<see cref="Encoding.Default"/></param>
        /// <param name="includeHeaders">使用头部标题</param>
        public static void Rfc4180Writer(this DataTable sourceTable, string filePath, bool isAppend = true, bool includeHeaders = true,Encoding? encoding = null)
        {
            FileHelper.FileDirectoryPathExistsAndCreate(filePath);
            if(encoding == null)
            {
                encoding = Encoding.Default;
            }
            using (StreamWriter writer = new StreamWriter(filePath,isAppend,encoding))
            {
                Rfc4180Writer(sourceTable, writer, includeHeaders);
            }
        }

        /// <summary>
        /// 以Rfc4180标准写入,参考：<see href="https://www.codeproject.com/Tips/665519/Writing-a-DataTable-to-a-CSV-file"/>
        /// <code>
        /// using (StreamWriter writer = new StreamWriter("C:\\Temp\\dump.csv")) {
        ///     Rfc4180Writer.WriteDataTable(sourceTable, writer, true);
        /// }
        /// </code>
        /// </summary>
        /// <param name="sourceTable">数据源</param>
        /// <param name="writer"></param>
        /// <param name="includeHeaders">使用头部标题</param>
        public static void Rfc4180Writer(this DataTable sourceTable, TextWriter writer, bool includeHeaders = true)
        {
            if (includeHeaders)
            {
                IEnumerable<String> headerValues = sourceTable.Columns
                    .OfType<DataColumn>()
                    .Select(column => QuoteValue(column.ColumnName));

                writer.WriteLine(String.Join(",", headerValues));
            }

            IEnumerable<String>? items = null;

            foreach (DataRow row in sourceTable.Rows)
            {
                items = row.ItemArray.Select(o => QuoteValue(o?.ToString() ?? String.Empty));
                writer.WriteLine(String.Join(",", items));
            }

            writer.Flush();
        }

        /// <summary>
        /// 引用值
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private static string QuoteValue(string value)
        {
            return String.Concat("\"",
            value.Replace("\"", "\"\""), "\"");
        }
    }

}
